<template>
	<div class="points-exchange-container">
		<div class="points-exchange-content">
			<!-- 查询条件 -->
			<t-form ref="form" :data="queryParams" label-width="80px" layout="inline" class="search-form" colon>
				<t-row style="width: 100%">
					<t-col :span="3">
						<t-form-item label="状态">
							<t-select
								v-model="queryParams.status"
								placeholder="请选择状态"
								clearable
								style="width: 158px"
							>
								<t-option
									v-for="(label, value) in PointsGoodsExchangeStatusLabels"
									:key="value"
									:value="value"
									:label="label"
								>
									{{ label }}
								</t-option>
							</t-select>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item>
							<t-space>
								<t-button theme="primary" @click="handleSearch"> 查询 </t-button>
								<t-button variant="base" @click="handleReset"> 重置 </t-button>
							</t-space>
						</t-form-item>
					</t-col>

					<t-col :span="3"></t-col>
					<t-col :span="3">
						<t-row justify="end">
							<t-button theme="primary" variant="base" @click="handleExport">
								<template #icon>
									<t-icon name="download" />
								</template>
								导出
							</t-button>
						</t-row>
					</t-col>
				</t-row>
			</t-form>

			<!-- 积分兑换列表表格 -->
			<div class="points-exchange-table">
				<t-table
					row-key="id"
					bordered
					height="calc(100vh - 55px - 28px - 28px - 16px - 64px - 70px)"
					:data="exchangeList"
					:columns="columns"
					:loading="loading"
					:pagination="pagination"
					@page-change="onPageChange"
				>
					<!-- 状态列 -->
					<template #status="{ row }">
						<t-tag :theme="getStatusTheme(row.status)">
							{{ PointsGoodsExchangeStatusLabels[row.status] || row.status }}
						</t-tag>
					</template>

					<!-- 积分数格式化 -->
					<template #points="{ row }">
						<span class="points-text">{{ Number(row.points || 0).toLocaleString() }} 积分</span>
					</template>

					<!-- 用户信息 -->
					<template #userInfo="{ row }">
						<div>
							<div>{{ row.userNickname || '-' }}</div>
							<div style="font-size: 12px; color: #999; margin-top: 2px;">
								{{ row.userPhone ? row.userPhone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : '-' }}
							</div>
						</div>
					</template>

					<!-- 商品信息 -->
					<template #goodsInfo="{ row }">
						<div style="display: flex; align-items: center;">
							<img
								v-if="row.goodsImage"
								:src="row.goodsImage"
								:alt="row.goodsName"
								style="width: 40px; height: 40px; border-radius: 4px; margin-right: 8px; object-fit: cover;"
							/>
							<div>
								<div style="font-weight: 500;">{{ row.goodsName || '-' }}</div>
								<div style="font-size: 12px; color: #999; margin-top: 2px;">
									数量: {{ row.quantity || 1 }}
								</div>
							</div>
						</div>
					</template>

					<!-- 收货地址 -->
					<template #address="{ row }">
						<div style="max-width: 200px;">
							<div>{{ row.receiverName || '-' }}</div>
							<div style="font-size: 12px; color: #999; margin-top: 2px;">
								{{ row.receiverPhone || '-' }}
							</div>
							<div style="font-size: 12px; color: #999; margin-top: 2px;">
								{{ row.receiverAddress || '-' }}
							</div>
						</div>
					</template>

					<!-- 操作列 -->
					<template #op="{ row }">
						<div style="display: flex;">
							<t-button theme="primary" variant="text" @click="handleEdit(row)">
								修改状态
							</t-button>
						</div>
					</template>
				</t-table>
			</div>
		</div>
	</div>
</template>

<script>
import {
	getPointsExchangePage,
	// deleteExchange,
	updateExchangeStatus,
	exportPointsExchange,
	PointsGoodsExchangeStatus,
	PointsGoodsExchangeStatusLabels,
} from '@/api/points-exchange';
import { DialogPlugin as TDialog, MessagePlugin } from 'tdesign-vue';

export default {
	name: 'PointsExchange',
	data() {
		return {
			loading: false,
			exchangeList: [],
			PointsGoodsExchangeStatus,
			PointsGoodsExchangeStatusLabels,
			selectedStatus: '', // 选中的状态值，每次弹框打开时清空

			// 查询参数
			queryParams: {
				status: null,
			},

			// 表格列配置
			columns: [
				{
					colKey: 'userInfo',
					title: '用户名',
					width: 150,
					cell: (h, { row }) => row?.user?.wechat?.nickname ?? ''
				},
				{
					colKey: 'goodsInfo',
					title: '商品名称',
					width: 200,
					cell: (h, { row }) => row?.goods?.name ?? ''
				},
				{ colKey: 'points', title: '兑换积分', width: 120, align: 'center', cell: (h, { row }) =>  {
					const title = row?.title ?? '';
					// 从title中提取数字
					const price = title.match(/\d+/)?.[0] ?? 0;
					return price;
				} },
				{ colKey: 'status', title: '状态', width: 100, align: 'center' },
				{ colKey: 'createdAt', title: '兑换时间', width: 180 },
				{ colKey: 'op', title: '操作', width: 120, fixed: 'right' },
			],

			// 分页配置
			pagination: {
				current: 1,
				pageSize: 10,
				total: 0,
				showJumper: true,
				showPageSize: true,
				pageSizeOptions: [10, 20, 50, 100],
			},
		};
	},

	mounted() {
		this.loadExchangeList();
	},

	methods: {
		// 加载积分兑换列表
		async loadExchangeList() {
			try {
				this.loading = true;
				const params = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
					...this.queryParams,
				};

				// 如果status没有值则删除
				if (!params?.status) {
					delete params.status;
				}

				const response = await getPointsExchangePage(params);

				// 参考 feedback 的数据处理方式
				if (response && response.data && response.data.data) {
					this.exchangeList = Array.isArray(response.data.data.data) ? response.data.data.data : [];
					this.pagination.total = Number(response.data.data.total) || 0;
					this.pagination.current = Number(response.data.data.page) || this.pagination.current;
					this.pagination.pageSize = Number(response.data.data.pageSize) || this.pagination.pageSize;
				} else {
					this.exchangeList = [];
					this.pagination.total = 0;
				}
			} catch (error) {
				console.error('加载积分兑换列表失败:', error);
				MessagePlugin.error('加载积分兑换列表失败');
				this.exchangeList = [];
				this.pagination.total = 0;
			} finally {
				this.loading = false;
			}
		},

		// 搜索
		handleSearch() {
			this.pagination.current = 1;
			this.loadExchangeList();
		},

		// 重置
		handleReset() {
			this.queryParams = {
				status: null,
			};
			this.pagination.current = 1;
			this.loadExchangeList();
		},

		// 分页变化
		onPageChange({ current, pageSize }) {
			this.pagination.current = current;

			if (pageSize !== this.pagination.pageSize) {
				this.pagination.current = 1;
			}

			this.pagination.pageSize = pageSize;

			this.loadExchangeList();
		},

		// 编辑兑换状态
		async handleEdit(row) {
			// 每次打开弹框时清空选中状态
			this.selectedStatus = '';

			const statusOptions = [
				{ label: '待处理', value: PointsGoodsExchangeStatus.PENDING },
				{ label: '已处理', value: PointsGoodsExchangeStatus.APPROVED },
				{ label: '已完成', value: PointsGoodsExchangeStatus.COMPLETED },
				{ label: '已取消', value: PointsGoodsExchangeStatus.CANCELLED },
				{ label: '已拒绝', value: PointsGoodsExchangeStatus.REJECTED },
			];

			const currentStatus = row.status;
			let dialogInstance = null;

			try {
				// 创建状态选择对话框
				dialogInstance = await new Promise((resolve) => {
					const instance = TDialog.confirm({
						header: '修改兑换状态',
						body: () => {
							return this.$createElement(
								'div',
								{
									style: { padding: '16px 0' },
								},
								[
									this.$createElement(
										'div',
										{
											style: { marginBottom: '16px' },
										},
										[
											this.$createElement(
												'span',
												{
													style: {
														display: 'inline-block',
														minWidth: '80px',
														color: '#666',
													},
												},
												'当前状态：'
											),
											this.$createElement(
												't-tag',
												{
													props: {
														theme: this.getStatusTheme(currentStatus),
													},
												},
												PointsGoodsExchangeStatusLabels[currentStatus]
											),
										]
									),
									this.$createElement('div', [
										this.$createElement(
											'label',
											{
												style: {
													display: 'block',
													marginBottom: '8px',
													color: '#333',
													fontWeight: '500',
												},
											},
											'选择新状态：'
										),
										this.$createElement(
											't-select',
											{
												props: {
													value: this.selectedStatus,
													placeholder: '请选择状态',
													style: { width: '100%' },
												},
												on: {
													change: (value) => {
														this.selectedStatus = value;
													},
												},
											},
											statusOptions.map((option) =>
												this.$createElement(
													't-option',
													{
														key: option.value,
														props: {
															value: option.value,
															label: option.label,
														},
													},
													option.label
												)
											)
										),
									]),
								]
							);
						},
						confirmBtn: {
							content: '确定修改',
							loading: false,
						},
						cancelBtn: '取消',
						onConfirm: () => {
							resolve(instance);
						},
						onCancel: () => {
							resolve(null);
						},
					});
				});

				// 用户取消操作
				if (!dialogInstance) {
					return;
				}

				if (!this.selectedStatus) {
					MessagePlugin.warning('请选择状态');
					return;
				}

				if (this.selectedStatus === currentStatus) {
					MessagePlugin.warning('请选择不同的状态');
					return;
				}

				// 显示加载状态
				dialogInstance.update({
					confirmBtn: {
						content: '修改中...',
						loading: true,
					},
				});

				const res = await updateExchangeStatus({id: row.id, status: this.selectedStatus });

				// 判断是否修改成功
				if (res && res.data && res.data.code === 200) {
					MessagePlugin.success('状态修改成功');
					this.loadExchangeList();
					dialogInstance.hide();
				} else {
					// 修改失败
					const errorMsg = res?.data?.message || '修改失败，请重试';
					MessagePlugin.error(errorMsg);

					// 恢复按钮状态
					dialogInstance.update({
						confirmBtn: {
							content: '确定修改',
							loading: false,
						},
					});
					return;
				}
			} catch (error) {
				console.error('修改兑换状态失败:', error);
				MessagePlugin.error('修改兑换状态失败');

				// 如果对话框还存在，恢复按钮状态
				if (dialogInstance && typeof dialogInstance.update === 'function') {
					dialogInstance.update({
						confirmBtn: {
							content: '确定修改',
							loading: false,
						},
					});
				}
				return;
			}
		},

		// 删除兑换记录
		async handleDelete(row) {
			const confirmDialog = TDialog.confirm({
				header: '确认删除',
				body: `确定要删除用户"${row.userNickname || '未知用户'}"的兑换记录吗？此操作不可撤销。`,
				confirmBtn: {
					content: '删除',
					theme: 'danger',
				},
				cancelBtn: '取消',
			});

			try {
				await confirmDialog;

				// 显示删除中状态
				confirmDialog.update({
					confirmBtn: {
						content: '删除中...',
						theme: 'danger',
						loading: true,
					},
				});

				// 调用删除API
				// const res = await deleteExchange(row.id);
				// confirmDialog.hide();
				// MessagePlugin.success('删除成功');
				// // 重新加载兑换列表
				// await this.loadExchangeList();
			} catch (error) {
				console.error('删除兑换记录失败:', error);

				// 根据错误类型显示不同的错误信息
				let errorMessage = '删除失败';
				if (error.message) {
					errorMessage = error.message;
				} else if (error.response?.data?.message) {
					errorMessage = error.response.data.message;
				} else if (error.response?.status === 403) {
					errorMessage = '没有权限删除此记录';
				} else if (error.response?.status === 409) {
					errorMessage = '该记录正在被使用，无法删除';
				} else if (error.code === 'NETWORK_ERROR') {
					errorMessage = '网络连接失败，请检查网络后重试';
				}

				MessagePlugin.error(errorMessage);

				// 如果对话框还存在，隐藏它
				if (confirmDialog && typeof confirmDialog.hide === 'function') {
					confirmDialog.hide();
				}
			}
		},

		// 获取状态主题色
		getStatusTheme(status) {
			const themeMap = {
				[PointsGoodsExchangeStatus.PENDING]: 'warning',
				[PointsGoodsExchangeStatus.APPROVED]: 'primary',
				[PointsGoodsExchangeStatus.COMPLETED]: 'success',
				[PointsGoodsExchangeStatus.CANCELLED]: 'danger',
				[PointsGoodsExchangeStatus.REJECTED]: 'danger',
			};
			return themeMap[status] || 'default';
		},

		// 导出
		async handleExport() {
			try {
				// 显示导出中状态
				this.loading = true;

				// 获取当前查询状态，如果有值则传入
				const status = this.queryParams.status || null;

				// 调用导出接口
				const response = await exportPointsExchange(status);

				// 创建下载链接
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				});
				const url = window.URL.createObjectURL(blob);
				const link = document.createElement('a');
				link.href = url;

				// 生成文件名
				const now = new Date();
				const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
				const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
				const statusText = status ? `_${PointsGoodsExchangeStatusLabels[status] || status}` : '';
				link.download = `积分兑换记录${statusText}_${dateStr}_${timeStr}.xlsx`;

				// 触发下载
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				window.URL.revokeObjectURL(url);

				MessagePlugin.success('导出成功');
			} catch (error) {
				console.error('导出失败:', error);
				MessagePlugin.error('导出失败，请重试');
			} finally {
				this.loading = false;
			}
		},
	},
};
</script>

<style lang="less" scoped>
.points-exchange-container {
	padding: 16px;
	background: #fff;
}

.points-exchange-content {
	.search-form {
		margin-bottom: 16px;
		padding: 16px;
		background: #f8f9fa;
		border-radius: 8px;
	}

	.points-exchange-table {
		.points-text {
			font-weight: 600;
			color: #ff6b35;
		}
	}
}
</style>